package com.sunther.document.interceptor;

import com.sunther.document.entity.User;
import com.sunther.document.service.UserService;
import com.sunther.document.util.JwtUtils;
import com.sunther.document.util.UserInfoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author csb
 * @description: TODO
 * @date 2023/5/9 16:39
 */
public class JwtInterceptor implements AsyncHandlerInterceptor {

    @Resource
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");

        if (StringUtils.isBlank(token)) {
            return false;
        }
        // 获取 token中的userId,根据userId查询数据库，检查用户是否存在
        Integer userId = UserInfoUtil.getUserId(request);
        User user = userService.getById(userId);
        if (user == null) {
            return false;
        }

        // 验证 token
        return jwtUtils.parseJWT(token);
    }


}
